package com.mzj.saas.rent;

import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.repository.core.AjaxResult;
import com.haixiaoke.saas.repository.core.BaseController;
import com.haixiaoke.saas.repository.core.page.TableDataInfo;
import com.haixiaoke.saas.repository.pojo.ApartmentLabel;
import com.haixiaoke.saas.repository.service.IApartmentLabelService;
import com.mzj.saas.annotation.CheckAuth;
import com.mzj.saas.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 公寓标签Controller
 *
 * @author qixi
 * @date 2023-05-11
 */
@RestController
@RequestMapping("/apartment/label")
public class ApartmentLabelController extends BaseController {

    @Autowired
    private IApartmentLabelService apartmentLabelService;
    @Autowired
    private LoginUserUtil loginUserUtil;


    /**
     * 查询公寓标签列表
     */
    @GetMapping("/list")
    @CheckAuth
    public TableDataInfo list(ApartmentLabel apartmentLabel) {
        startPage();
        List<ApartmentLabel> list = apartmentLabelService.selectApartmentLabelList(apartmentLabel);
        return getDataTable(list);
    }


    /**
     * 获取公寓标签详细信息
     */
    @GetMapping(value = "/{labelId}")
    @CheckAuth
    public AjaxResult getInfo(@PathVariable("labelId") Long labelId) {
        return success(apartmentLabelService.selectApartmentLabelByLabelId(labelId));
    }

    /**
     * 获取机构下的标签
     */
    @GetMapping(value = "/getOrgId/{orgId}")
    @CheckAuth
    public AjaxResult getApartmentLabelsByOrgId(@PathVariable("orgId") Long orgId) {
        List<ApartmentLabel> list = apartmentLabelService.selectApartmentLabelByOrgIdId(orgId);
        return success(list);
    }

    /**
     * 新增公寓标签
     */
    @PostMapping
    @CheckAuth
    public AjaxResult add(@Valid @RequestBody ApartmentLabel apartmentLabel) {
        String id = loginUserUtil.getId();
        apartmentLabel.setCreateBy(id);
        String labelName = apartmentLabel.getLabelName();

        if (StrUtil.isBlank(labelName)) {
            return error("标签名不得为空");
        }
        if (StrUtil.length(labelName) > 10) {
            return error("标签长度不得大于10个字");
        }
        if (!apartmentLabelService.checkOrgIdLabelNameUnique(apartmentLabel.getOrgId(), labelName)) {
            return error("标签已存在");
        }
        int flag = apartmentLabelService.insertApartmentLabel(apartmentLabel);
        if (flag == 0) {
            return error();
        }
        return success(apartmentLabel);
    }


    /**
     * 删除公寓标签
     */
    @DeleteMapping("/{labelId}")
    @CheckAuth
    public AjaxResult remove(@PathVariable Long labelId) {
        return toAjax(apartmentLabelService.deleteApartmentLabelByLabelId(labelId));
    }
}
